package com.ruoyi.web.controller.eduManage;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.*;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import com.ruoyi.eduManage.domain.vo.EduHomeworkSubmitExportVO;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.eduManage.domain.EduClass;
import com.ruoyi.eduManage.domain.EduStudent;
import com.ruoyi.eduManage.domain.EduHomeworkSubmit;
import com.ruoyi.eduManage.domain.vo.EduHomeworkSubmitImportVo;
import com.ruoyi.eduManage.domain.vo.EduHomeworkSubmitVO;
import com.ruoyi.eduManage.domain.vo.HomeworkImportResultVO;
import com.ruoyi.eduManage.service.IEduClassService;
import com.ruoyi.eduManage.service.IEduStudentService;
import com.ruoyi.eduManage.service.IEduHomeworkSubmitService;
import com.ruoyi.eduManage.service.IEduStudentPointsLogService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

import java.text.SimpleDateFormat;

/**
 * 作业提交记录Controller
 *
 * @author ruoyi
 * @date 2025-10-27
 */
@RestController
@RequestMapping("/eduManage/submit")
public class EduHomeworkSubmitController extends BaseController
{
    @Autowired
    private IEduHomeworkSubmitService eduHomeworkSubmitService;

    @Autowired
    private IEduClassService eduClassService;

    @Autowired
    private IEduStudentService eduStudentService;

    @Autowired
    private IEduStudentPointsLogService pointsLogService;

    /**
     * 查询作业提交记录列表
     */
    @PreAuthorize("@ss.hasPermi('eduManage:submit:list')")
    @GetMapping("/list")
    public TableDataInfo list(EduHomeworkSubmit eduHomeworkSubmit)
    {
        startPage();
        List<EduHomeworkSubmit> list = eduHomeworkSubmitService.selectEduHomeworkSubmitList(eduHomeworkSubmit);
        TableDataInfo tableDataInfo = getDataTable(list);
        List<EduHomeworkSubmitVO> voList = eduHomeworkSubmitService.convertToVOList(list);
        tableDataInfo.setRows(voList);
        return tableDataInfo;
    }

    /**
     * 导出作业提交记录列表
     */
    @PreAuthorize("@ss.hasPermi('eduManage:submit:export')")
    @Log(title = "作业提交记录", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, EduHomeworkSubmit eduHomeworkSubmit)
    {
        List<EduHomeworkSubmit> list = eduHomeworkSubmitService.selectEduHomeworkSubmitList(eduHomeworkSubmit);
        List<EduHomeworkSubmitVO> voList = eduHomeworkSubmitService.convertToVOList(list);
        ExcelUtil<EduHomeworkSubmitVO> util = new ExcelUtil<EduHomeworkSubmitVO>(EduHomeworkSubmitVO.class);
        util.exportExcel(response, voList, "作业提交记录数据");
    }

    /**
     * 导入作业提交记录
     */
    @PreAuthorize("@ss.hasPermi('eduManage:submit:import')")
    @Log(title = "作业提交记录", businessType = BusinessType.IMPORT)
    @PostMapping("/importData")
    public AjaxResult importData(@RequestParam("file") MultipartFile file, @RequestParam String classCode, @RequestParam String dueDate)
    {
        try
        {
            HomeworkImportResultVO result = eduHomeworkSubmitService.importHomeworkSubmit(file, classCode, dueDate);
            return AjaxResult.success("导入成功！成功导入" + result.getSuccessCount() + "条记录，失败" + result.getFailCount() + "条记录", result);
        }
        catch (Exception e)
        {
            return AjaxResult.error("导入失败：" + e.getMessage());
        }
    }

    /**
     * 下载导入模板
     * @param response HTTP响应
     * @param classCode 班级编码
     */
    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response, @RequestParam String classCode) throws IOException, UnsupportedEncodingException
    {
        // 1. 验证班级是否存在
        EduClass eduClass = new EduClass();
        eduClass.setClassCode(classCode);
        List<EduClass> classList = eduClassService.selectEduClassList(eduClass);
        if (classList == null || classList.isEmpty()) {
            throw new ServiceException("班级不存在");
        }

        // 2. 查询该班级的在读学生
        EduStudent queryStudent = new EduStudent();
        queryStudent.setClassId(classCode);
        queryStudent.setStatus("0"); // 0表示在读
        List<EduStudent> studentList = eduStudentService.selectEduStudentList(queryStudent);

        // 3. 生成模板数据
        List<EduHomeworkSubmitImportVo> templateData = new ArrayList<>();
        for (EduStudent student : studentList) {
            EduHomeworkSubmitImportVo vo = new EduHomeworkSubmitImportVo();
            vo.setStudentNo(student.getStudentNo());
            vo.setStudentName(student.getStudentName());
            templateData.add(vo);
        }

        // 4. 生成Excel并设置文件名
        ExcelUtil<EduHomeworkSubmitImportVo> util = new ExcelUtil<>(EduHomeworkSubmitImportVo.class);
        util.exportExcel(response, templateData, "作业提交记录");
    }

    /**
     * 获取作业提交记录详细信息
     */
    @PreAuthorize("@ss.hasPermi('eduManage:submit:query')")
    @GetMapping(value = "/{submitId}")
    public AjaxResult getInfo(@PathVariable("submitId") Long submitId)
    {
        EduHomeworkSubmit submit = eduHomeworkSubmitService.selectEduHomeworkSubmitBySubmitId(submitId);
        EduHomeworkSubmitVO vo = eduHomeworkSubmitService.convertToVO(submit);
        return success(vo);
    }

    /**
     * 新增作业提交记录
     */
    @PreAuthorize("@ss.hasPermi('eduManage:submit:add')")
    @Log(title = "作业提交记录", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody EduHomeworkSubmit eduHomeworkSubmit)
    {
        return toAjax(eduHomeworkSubmitService.insertEduHomeworkSubmit(eduHomeworkSubmit));
    }

    /**
     * 修改作业提交记录
     */
    @PreAuthorize("@ss.hasPermi('eduManage:submit:edit')")
    @Log(title = "作业提交记录", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody EduHomeworkSubmit eduHomeworkSubmit)
    {
        return toAjax(eduHomeworkSubmitService.updateEduHomeworkSubmit(eduHomeworkSubmit));
    }

    /**
     * 删除作业提交记录
     */
    @PreAuthorize("@ss.hasPermi('eduManage:submit:remove')")
    @Log(title = "作业提交记录", businessType = BusinessType.DELETE)
	@DeleteMapping("/{submitIds}")
    public AjaxResult remove(@PathVariable Long[] submitIds)
    {
        return toAjax(eduHomeworkSubmitService.deleteEduHomeworkSubmitBySubmitIds(submitIds));
    }

    /**
     * 获取数据统计概览
     */
    @GetMapping("/statistics/overview")
    public AjaxResult getStatisticsOverview(@RequestParam(required = false) String startDate,
                                          @RequestParam(required = false) String endDate,
                                          @RequestParam(required = false) String classCode)
    {
        try {
            // 构建查询条件
            EduHomeworkSubmit query = new EduHomeworkSubmit();
            if (classCode != null && !classCode.isEmpty()) {
                query.setClassCode(classCode);
            }

            // 设置日期范围查询参数
            Map<String, Object> params = new HashMap<>();
            if (startDate != null && !startDate.isEmpty()) {
                params.put("beginSubmitDate", startDate);
            }
            if (endDate != null && !endDate.isEmpty()) {
                params.put("endSubmitDate", endDate);
            }
            query.setParams(params);

            // 查询所有符合条件的提交记录
            List<EduHomeworkSubmit> allSubmits = eduHomeworkSubmitService.selectEduHomeworkSubmitList(query);

            // 统计数据
            Map<String, Object> overview = new HashMap<>();

            // 总学生数（去重）
            long totalStudents = allSubmits.stream()
                .map(EduHomeworkSubmit::getStudentNo)
                .distinct()
                .count();

            // 已提交作业的学生数（去重，排除状态为"0"未交的）
            long submittedStudents = allSubmits.stream()
                .filter(submit -> !"0".equals(submit.getSubmitStatus()))
                .map(EduHomeworkSubmit::getStudentNo)
                .distinct()
                .count();

            // 按时提交的学生数（状态为"1"按时提交）
            long ontimeStudents = allSubmits.stream()
                .filter(submit -> "1".equals(submit.getSubmitStatus()))
                .map(EduHomeworkSubmit::getStudentNo)
                .distinct()
                .count();

            // 迟交的学生数（状态为"2"迟交）
            long lateStudents = allSubmits.stream()
                .filter(submit -> "2".equals(submit.getSubmitStatus()))
                .map(EduHomeworkSubmit::getStudentNo)
                .distinct()
                .count();

            // 计算百分比
            double submitRate = totalStudents > 0 ? (double) submittedStudents / totalStudents * 100 : 0;
            double ontimeRate = totalStudents > 0 ? (double) ontimeStudents / totalStudents * 100 : 0;
            double lateRate = totalStudents > 0 ? (double) lateStudents / totalStudents * 100 : 0;

            overview.put("totalStudents", totalStudents);
            overview.put("submittedStudents", submittedStudents);
            overview.put("ontimeStudents", ontimeStudents);
            overview.put("lateStudents", lateStudents);
            overview.put("submitRate", Math.round(submitRate * 100.0) / 100.0);
            overview.put("ontimeRate", Math.round(ontimeRate * 100.0) / 100.0);
            overview.put("lateRate", Math.round(lateRate * 100.0) / 100.0);

            return AjaxResult.success(overview);
        } catch (Exception e) {
            return AjaxResult.error("获取统计概览失败：" + e.getMessage());
        }
    }

    /**
     * 获取提交统计数据
     */
    @GetMapping("/statistics/submit")
    public AjaxResult getSubmitStatistics(@RequestParam(required = false) String startDate,
                                        @RequestParam(required = false) String endDate,
                                        @RequestParam(required = false) String classCode)
    {
        try {
            // 构建查询条件
            EduHomeworkSubmit query = new EduHomeworkSubmit();
            if (classCode != null && !classCode.isEmpty()) {
                query.setClassCode(classCode);
            }

            // 设置日期范围查询参数
            Map<String, Object> params = new HashMap<>();
            if (startDate != null && !startDate.isEmpty()) {
                params.put("beginSubmitDate", startDate);
            }
            if (endDate != null && !endDate.isEmpty()) {
                params.put("endSubmitDate", endDate);
            }
            query.setParams(params);

            // 查询所有符合条件的提交记录
            List<EduHomeworkSubmit> allSubmits = eduHomeworkSubmitService.selectEduHomeworkSubmitList(query);

            // 按学生分组统计
            Map<String, Map<String, Object>> studentStats = new HashMap<>();

            for (EduHomeworkSubmit submit : allSubmits) {
                String studentKey = submit.getStudentNo() + "_" + submit.getStudentName();

                studentStats.computeIfAbsent(studentKey, k -> {
                    Map<String, Object> stats = new HashMap<>();
                    stats.put("studentNo", submit.getStudentNo());
                    stats.put("studentName", submit.getStudentName());
                    stats.put("className", submit.getClassName());
                    stats.put("totalSubmits", 0);
                    stats.put("ontimeSubmits", 0);
                    stats.put("lateSubmits", 0);
                    stats.put("unsubmittedCount", 0);
                    return stats;
                });

                Map<String, Object> stats = studentStats.get(studentKey);

                // 统计提交情况
                if (!"0".equals(submit.getSubmitStatus())) {
                    stats.put("totalSubmits", (Integer) stats.get("totalSubmits") + 1);

                    if ("1".equals(submit.getSubmitStatus())) {
                        stats.put("ontimeSubmits", (Integer) stats.get("ontimeSubmits") + 1);
                    } else if ("2".equals(submit.getSubmitStatus())) {
                        stats.put("lateSubmits", (Integer) stats.get("lateSubmits") + 1);
                    }
                } else {
                    stats.put("unsubmittedCount", (Integer) stats.get("unsubmittedCount") + 1);
                }
            }

            // 计算提交率
            for (Map<String, Object> stats : studentStats.values()) {
                int total = (Integer) stats.get("totalSubmits") + (Integer) stats.get("unsubmittedCount");
                int submitted = (Integer) stats.get("totalSubmits");
                int ontime = (Integer) stats.get("ontimeSubmits");
                int late = (Integer) stats.get("lateSubmits");

                double submitRate = total > 0 ? (double) submitted / total * 100 : 0;
                double ontimeRate = total > 0 ? (double) ontime / total * 100 : 0;
                double lateRate = total > 0 ? (double) late / total * 100 : 0;

                stats.put("submitRate", Math.round(submitRate * 100.0) / 100.0);
                stats.put("ontimeRate", Math.round(ontimeRate * 100.0) / 100.0);
                stats.put("lateRate", Math.round(lateRate * 100.0) / 100.0);
            }

            return AjaxResult.success(new ArrayList<>(studentStats.values()));
        } catch (Exception e) {
            return AjaxResult.error("获取提交统计失败：" + e.getMessage());
        }
    }

    /**
     * 导出统计数据 - 每天数据单独显示为列
     */
    @PreAuthorize("@ss.hasPermi('eduManage:submit:export')")
    @Log(title = "作业提交统计", businessType = BusinessType.EXPORT)
    @PostMapping("/statistics/export")
    public void exportStatistics(HttpServletResponse response,
                                @RequestParam(required = false) String startDate,
                                @RequestParam(required = false) String endDate,
                                @RequestParam(required = false) String classCode,
                                @RequestParam(required = false) String studentName,
                                @RequestParam(required = false, defaultValue = "5") Integer expectedDays)
    {
        try {
            // 获取每日提交详情数据用于导出（导出场景不按学生姓名过滤）
            AjaxResult result = getDailySubmitDetail(startDate, endDate, classCode, studentName, expectedDays);
            @SuppressWarnings("unchecked")
            Map<String, Object> data = (Map<String, Object>) result.get("data");
            @SuppressWarnings("unchecked")
            List<Map<String, Object>> studentData = (List<Map<String, Object>>) data.get("studentData");
            @SuppressWarnings("unchecked")
            List<String> dateColumns = (List<String>) data.get("dateColumns");

            // 使用Apache POI直接创建Excel文件，支持动态列
            Workbook workbook = new XSSFWorkbook();
            Sheet sheet = workbook.createSheet("学生作业提交统计");

            // 创建表头
            Row headerRow = sheet.createRow(0);
            int colIndex = 0;

            // 基本信息列
            headerRow.createCell(colIndex++).setCellValue("学生姓名");
            headerRow.createCell(colIndex++).setCellValue("英文名");
            headerRow.createCell(colIndex++).setCellValue("班级ID");

            // 为每个日期创建两列：提交状态和奖励分数
            for (String date : dateColumns) {
                String dateLabel = date.substring(5).replace("-", ".");
                headerRow.createCell(colIndex++).setCellValue(dateLabel + "");
                headerRow.createCell(colIndex++).setCellValue("奖励积分");
            }

            // 统计信息列
            headerRow.createCell(colIndex++).setCellValue("总提交次数");
            headerRow.createCell(colIndex++).setCellValue("总奖励分数");
            headerRow.createCell(colIndex++).setCellValue("打卡率");
            headerRow.createCell(colIndex++).setCellValue("应打卡次数");

            // 填充数据行
            int rowIndex = 1;
            for (Map<String, Object> student : studentData) {
                Row dataRow = sheet.createRow(rowIndex++);
                colIndex = 0;

                // 基本信息
                dataRow.createCell(colIndex++).setCellValue((String) student.get("studentName"));
                dataRow.createCell(colIndex++).setCellValue((String) student.get("englishName"));
                dataRow.createCell(colIndex++).setCellValue((String) student.get("classId"));

                // 每日数据
                @SuppressWarnings("unchecked")
                Map<String, Object> dailyData = (Map<String, Object>) student.get("dailyData");
                @SuppressWarnings("unchecked")
                Map<String, Integer> rewardData = (Map<String, Integer>) student.get("rewardData");

                for (String date : dateColumns) {
                    // 提交状态列
                    String submitStatus = "❌";
                    if (dailyData != null && dailyData.containsKey(date)) {
                        @SuppressWarnings("unchecked")
                        Map<String, Object> dayData = (Map<String, Object>) dailyData.get(date);
                        Boolean submitted = (Boolean) dayData.get("submitted");
                        Boolean isLate = (Boolean) dayData.get("isLate");

                        if (submitted) {
                            submitStatus = isLate != null && isLate ? "⭕" : "✅";
                        }
                    }
                    dataRow.createCell(colIndex++).setCellValue(submitStatus);

                    // 奖励分数列
                    Integer reward = 0;
                    if (rewardData != null && rewardData.containsKey(date)) {
                        reward = rewardData.get(date);
                    }
                    dataRow.createCell(colIndex++).setCellValue(reward);
                }

                // 统计信息
                dataRow.createCell(colIndex++).setCellValue((Integer) student.get("totalSubmits"));
                dataRow.createCell(colIndex++).setCellValue((Integer) student.get("totalRewardScore"));

                // 打卡率，添加%符号
                Double attendanceRate = (Double) student.get("attendanceRate");
                String attendanceRateStr = String.format("%.1f%%", attendanceRate);
                dataRow.createCell(colIndex++).setCellValue(attendanceRateStr);

                dataRow.createCell(colIndex++).setCellValue((Integer) student.get("expectedDays"));
            }

            // 自动调整列宽
            for (int i = 0; i < colIndex; i++) {
                sheet.autoSizeColumn(i);
            }

            // 设置响应头
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("utf-8");

            // 生成文件名
            String fileName = "学生作业提交统计_" + new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date()) + ".xlsx";
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + java.net.URLEncoder.encode(fileName, "UTF-8"));

            // 输出Excel文件
            workbook.write(response.getOutputStream());
            workbook.close();

        } catch (Exception e) {
            logger.error("导出统计数据失败", e);
        }
    }

    /**
     * 导出统计图片（PNG）- 使用每日详情的原始数据渲染
     */
    @PreAuthorize("@ss.hasPermi('eduManage:submit:export')")
    @Log(title = "作业提交统计图片", businessType = BusinessType.EXPORT)
    @PostMapping("/statistics/export/image")
    public void exportStatisticsImage(HttpServletResponse response,
                                      @RequestParam(required = false) String startDate,
                                      @RequestParam(required = false) String endDate,
                                      @RequestParam(required = false) String classCode,
                                      @RequestParam(required = false, defaultValue = "5") Integer expectedDays)
    {
        try {
            // 复用每日提交详情的数据源，确保与前端展示一致（图片导出不按学生姓名过滤）
            AjaxResult result = getDailySubmitDetail(startDate, endDate, classCode, null, expectedDays);
            @SuppressWarnings("unchecked")
            Map<String, Object> data = (Map<String, Object>) result.get("data");
            @SuppressWarnings("unchecked")
            List<Map<String, Object>> studentData = (List<Map<String, Object>>) data.get("studentData");
            @SuppressWarnings("unchecked")
            List<String> dateColumns = (List<String>) data.get("dateColumns");

            // 基本尺寸设置
            int leftInfoWidth = 380; // 左侧姓名/英文名/班级列宽
            int dateColWidth = 28;   // 每个日期列宽
            int rowHeight = 26;      // 每行高度
            int headerHeight = 60;   // 头部高度（标题 + 日期列头）
            int legendHeight = 30;   // 图例高度
            int padding = 10;        // 内边距

            int rows = (studentData != null ? studentData.size() : 0);
            int cols = (dateColumns != null ? dateColumns.size() : 0);

            int width = padding * 2 + leftInfoWidth + Math.max(cols, 1) * dateColWidth;
            int height = padding * 2 + headerHeight + legendHeight + Math.max(rows, 1) * rowHeight;

            // 创建画布
            java.awt.image.BufferedImage image = new java.awt.image.BufferedImage(width, height, java.awt.image.BufferedImage.TYPE_INT_ARGB);
            java.awt.Graphics2D g = image.createGraphics();
            g.setRenderingHint(java.awt.RenderingHints.KEY_ANTIALIASING, java.awt.RenderingHints.VALUE_ANTIALIAS_ON);

            // 背景
            g.setColor(java.awt.Color.WHITE);
            g.fillRect(0, 0, width, height);

            // 标题
            g.setColor(new java.awt.Color(51, 51, 51));
            java.awt.Font titleFont = new java.awt.Font("SansSerif", java.awt.Font.BOLD, 16);
            g.setFont(titleFont);
            String title = "学生作业提交统计";
            g.drawString(title, padding, padding + 20);

            // 图例
            int legendY = padding + 40;
            int legendX = padding;
            g.setFont(new java.awt.Font("SansSerif", java.awt.Font.PLAIN, 12));
            // 绿色：按时；橙色：迟交；灰色：未交
            g.setColor(new java.awt.Color(67, 160, 71));
            g.fillRect(legendX, legendY - 10, 14, 14);
            g.setColor(java.awt.Color.DARK_GRAY);
            g.drawString("按时", legendX + 20, legendY);

            g.setColor(new java.awt.Color(245, 124, 0));
            g.fillRect(legendX + 60, legendY - 10, 14, 14);
            g.setColor(java.awt.Color.DARK_GRAY);
            g.drawString("迟交", legendX + 80, legendY);

            g.setColor(new java.awt.Color(189, 189, 189));
            g.fillRect(legendX + 120, legendY - 10, 14, 14);
            g.setColor(java.awt.Color.DARK_GRAY);
            g.drawString("未交", legendX + 140, legendY);

            // 日期列头
            int headerY = padding + headerHeight - 20;
            int startX = padding + leftInfoWidth;
            g.setFont(new java.awt.Font("SansSerif", java.awt.Font.PLAIN, 12));
            g.setColor(new java.awt.Color(120, 120, 120));
            if (dateColumns != null) {
                for (int i = 0; i < dateColumns.size(); i++) {
                    String date = dateColumns.get(i);
                    String dateLabel = date.substring(5).replace("-", "."); // MM.dd
                    int x = startX + i * dateColWidth + 4;
                    g.drawString(dateLabel, x, headerY);
                }
            }

            // 分隔线
            g.setColor(new java.awt.Color(230, 230, 230));
            g.drawLine(padding, padding + headerHeight, width - padding, padding + headerHeight);

            // 左侧列头
            g.setColor(new java.awt.Color(100, 100, 100));
            g.setFont(new java.awt.Font("SansSerif", java.awt.Font.PLAIN, 13));
            g.drawString("学生姓名", padding + 6, padding + headerHeight - 22);
            g.drawString("英文名", padding + 136, padding + headerHeight - 22);
            g.drawString("班级ID", padding + 266, padding + headerHeight - 22);

            // 渲染数据行
            int y = padding + headerHeight + legendHeight;
            if (studentData != null) {
                for (Map<String, Object> student : studentData) {
                    // 左侧基本信息
                    g.setColor(new java.awt.Color(33, 33, 33));
                    g.setFont(new java.awt.Font("SansSerif", java.awt.Font.PLAIN, 13));
                    String sName = (String) student.get("studentName");
                    String eName = (String) student.get("englishName");
                    String classId = (String) student.get("classId");
                    if (sName != null) g.drawString(sName, padding + 6, y - 8);
                    if (eName != null) g.drawString(eName, padding + 136, y - 8);
                    if (classId != null) g.drawString(classId, padding + 266, y - 8);

                    @SuppressWarnings("unchecked")
                    Map<String, Object> dailyData = (Map<String, Object>) student.get("dailyData");

                    // 每日状态格子
                    if (dateColumns != null) {
                        for (int i = 0; i < dateColumns.size(); i++) {
                            String date = dateColumns.get(i);
                            int cellX = startX + i * dateColWidth + 4;
                            int cellY = y - rowHeight + 4;

                            java.awt.Color color = new java.awt.Color(189, 189, 189); // 未交默认灰色
                            if (dailyData != null && dailyData.containsKey(date)) {
                                @SuppressWarnings("unchecked")
                                Map<String, Object> dayData = (Map<String, Object>) dailyData.get(date);
                                Boolean submitted = (Boolean) dayData.get("submitted");
                                Boolean isLate = (Boolean) dayData.get("isLate");
                                if (submitted != null && submitted) {
                                    color = (isLate != null && isLate) ? new java.awt.Color(245, 124, 0) : new java.awt.Color(67, 160, 71);
                                }
                            }

                            g.setColor(color);
                            g.fillRoundRect(cellX, cellY, dateColWidth - 8, rowHeight - 8, 6, 6);
                        }
                    }

                    // 行分隔线
                    g.setColor(new java.awt.Color(240, 240, 240));
                    g.drawLine(padding, y, width - padding, y);

                    y += rowHeight;
                }
            }

            // 输出PNG
            response.setContentType("image/png");
            response.setCharacterEncoding("utf-8");
            String fileName = "学生作业提交统计_" + new java.text.SimpleDateFormat("yyyyMMdd_HHmmss").format(new java.util.Date()) + ".png";
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + java.net.URLEncoder.encode(fileName, "UTF-8"));

            javax.imageio.ImageIO.write(image, "png", response.getOutputStream());
            g.dispose();
        } catch (Exception e) {
            logger.error("导出统计图片失败", e);
        }
    }

    /**
     * 获取班级选项列表
     */
    @GetMapping("/statistics/classOptions")
    public AjaxResult getClassOptions()
    {
        try {
            EduClass query = new EduClass();
            query.setDelFlag("0"); // 只查询未删除的班级
            query.setIsClosed("0"); // 只查询未关班的班级
            List<EduClass> classList = eduClassService.selectEduClassList(query);

            List<Map<String, Object>> options = new ArrayList<>();
            for (EduClass eduClass : classList) {
                Map<String, Object> option = new HashMap<>();
                option.put("value", eduClass.getClassCode());
                option.put("label", eduClass.getClassName());
                options.add(option);
            }

            return AjaxResult.success(options);
        } catch (Exception e) {
            return AjaxResult.error("获取班级选项失败：" + e.getMessage());
        }
    }

    /**
     * 获取学生按班级列表
     */
    @GetMapping("/statistics/studentsByClass")
    public AjaxResult getStudentsByClass(@RequestParam String classCode)
    {
        try {
            EduStudent query = new EduStudent();
            query.setClassId(classCode);
            query.setDelFlag("0"); // 只查询未删除的学生
            List<EduStudent> studentList = eduStudentService.selectEduStudentList(query);

            List<Map<String, Object>> students = new ArrayList<>();
            for (EduStudent student : studentList) {
                Map<String, Object> studentInfo = new HashMap<>();
                studentInfo.put("studentNo", student.getStudentNo());
                studentInfo.put("studentName", student.getStudentName());
                students.add(studentInfo);
            }

            return AjaxResult.success(students);
        } catch (Exception e) {
            logger.error("获取班级学生列表失败", e);
            return AjaxResult.error("获取班级学生列表失败：" + e.getMessage());
        }
    }

    /**
     * 获取学生每日提交详情统计
     */
    @GetMapping("/statistics/dailyDetail")
    public AjaxResult getDailySubmitDetail(@RequestParam(required = false) String startDate,
                                         @RequestParam(required = false) String endDate,
                                         @RequestParam(required = false) String classCode,
                                         @RequestParam(required = false) String studentName,
                                         @RequestParam(required = false, defaultValue = "5") Integer expectedDays)
    {
        try {
            // 设置默认日期范围（最近7天）
            if (startDate == null || startDate.isEmpty()) {
                Calendar cal = Calendar.getInstance();
                cal.add(Calendar.DAY_OF_MONTH, -7);
                startDate = new SimpleDateFormat("yyyy-MM-dd").format(cal.getTime());
            }
            if (endDate == null || endDate.isEmpty()) {
                endDate = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
            }

            // 获取班级学生列表（支持按学生姓名过滤）
            EduStudent studentQuery = new EduStudent();
            if (classCode != null && !classCode.isEmpty()) {
                studentQuery.setClassId(classCode);
            }
            if (studentName != null && !studentName.isEmpty()) {
                studentQuery.setStudentName(studentName);
            }
            studentQuery.setDelFlag("0");
            List<EduStudent> studentList = eduStudentService.selectEduStudentList(studentQuery);

            // 获取日期范围内的提交记录（支持按学生姓名过滤）
            EduHomeworkSubmit submitQuery = new EduHomeworkSubmit();
            if (classCode != null && !classCode.isEmpty()) {
                submitQuery.setClassCode(classCode);
            }
            if (studentName != null && !studentName.isEmpty()) {
                submitQuery.setStudentName(studentName);
            }
            // 使用应交日期范围过滤查询数据
            Map<String, Object> params = new HashMap<>();
            params.put("beginDueDate", startDate);
            params.put("endDueDate", endDate);
            submitQuery.setParams(params);
            List<EduHomeworkSubmit> submitList = eduHomeworkSubmitService.selectEduHomeworkSubmitList(submitQuery);

            // 生成日期列表
            List<String> dateColumns = new ArrayList<>();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            Calendar start = Calendar.getInstance();
            Calendar end = Calendar.getInstance();
            start.setTime(sdf.parse(startDate));
            end.setTime(sdf.parse(endDate));

            while (!start.after(end)) {
                dateColumns.add(sdf.format(start.getTime()));
                start.add(Calendar.DAY_OF_MONTH, 1);
            }

            // 构建学生每日提交数据
            List<Map<String, Object>> studentData = new ArrayList<>();
            for (EduStudent student : studentList) {
                Map<String, Object> studentRow = new HashMap<>();
                studentRow.put("englishName", student.getEnglishName());
                studentRow.put("studentName", student.getStudentName());
                studentRow.put("classId", student.getClassId()); // 添加classId信息
                // studentRow.put("className", student.getClassName());

                // 统计总数
                int totalSubmits = 0;
                int lateSubmits = 0;
                int totalRewardScore = 0; // 总奖励积分

                // 为每个日期添加提交状态
                Map<String, Object> dailyData = new HashMap<>();
                // 单独存储奖励积分数据
                Map<String, Integer> rewardData = new HashMap<>();

                for (String date : dateColumns) {
                    Map<String, Object> dayInfo = new HashMap<>();
                    dayInfo.put("submitted", false);
                    dayInfo.put("isLate", false);

                    int dayScore = 0;

                    // 查找该学生在该日期的提交记录
                    for (EduHomeworkSubmit submit : submitList) {
                        if (student.getStudentNo().equals(submit.getStudentNo()) &&
                            submit.getDueDate() != null &&
                            date.equals(sdf.format(submit.getDueDate()))) {
                            // 提交状态约定：0 未交、1 已提交、2 迟交
                            boolean isSubmitted = "1".equals(submit.getSubmitStatus()) || "2".equals(submit.getSubmitStatus());
                            boolean isLate = "2".equals(submit.getSubmitStatus());

                            dayInfo.put("submitted", isSubmitted);
                            dayInfo.put("isLate", isLate);

                            if (isSubmitted) {
                                dayScore = submit.getScore() != null ? submit.getScore().intValue() : 0;
                                totalSubmits++;
                                totalRewardScore += dayScore;
                                if (isLate) {
                                    lateSubmits++;
                                }
                            }
                            break;
                        }
                    }

                    dailyData.put(date, dayInfo);
                    rewardData.put(date, dayScore);
                }

                studentRow.put("dailyData", dailyData);
                studentRow.put("rewardData", rewardData); // 单独的奖励积分数据
                studentRow.put("totalSubmits", totalSubmits);
                studentRow.put("lateSubmits", lateSubmits);
                studentRow.put("totalRewardScore", totalRewardScore); // 总奖励积分

                // 计算打卡率：实际提交次数 / 应打卡次数
                double attendanceRate = expectedDays > 0 ? (double) totalSubmits / expectedDays * 100 : 0;
                studentRow.put("attendanceRate", Math.round(attendanceRate * 100.0) / 100.0); // 保留两位小数
                studentRow.put("expectedDays", expectedDays); // 应打卡次数

                studentData.add(studentRow);
            }

            Map<String, Object> result = new HashMap<>();
            result.put("studentData", studentData);
            result.put("dateColumns", dateColumns);
            result.put("startDate", startDate);
            result.put("endDate", endDate);

            return AjaxResult.success(result);

        } catch (Exception e) {
            logger.error("获取学生每日提交详情失败", e);
            return AjaxResult.error("获取学生每日提交详情失败：" + e.getMessage());
        }
    }
}
